a_number = 12
a_string = 'hello' # Strings must be within quotations
a_pi = 3.14
# shows how to print a string message template
# prints variables separated by a new line
print(a_number, a_string, a_pi, sep="\n")
12 hello 3.14
Let's try to mix types and see what happens
# The below line will raise a 'TypeError'
a_number + a_string
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-82ebd5d786b4> in <module> 1 # The below line will raise a 'TypeError' ----> 2 a_number + a_string TypeError: unsupported operand type(s) for +: 'int' and 'str'
Since we do not declare types, runtime checks for types and does not allow invalid operations. TypeError is a type of expection, we will comeback to it when we learn about exception handling
.py extension and are called modules. hello.py, the easiest way to run it is with the shell command python hello.py Alice which calls the Python interpreter to execute the code in hello.py, passing it the command line argument Alice.import statementos builtin module and print the current working directoryimport os
curr_working_dir = os.getcwd()
print("Current Working Directory -", curr_working_dir)
Current Working Directory - d:\Users\Krishna_Alagiri\projects\Misc\CBSE-Computer-Science
from keyword can be used to import specific item within a modulefrom sys import version
print(version)
3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
We're using python3 for learning python. You don't have to worry about the os and sys right now.
greet_user() function accepts a variable username as argument/input and it prints a message.format() function used inside print function,is a predefined function used to replace {} with a data. Thats' why you see John Doe in the place of {} in the output stringdef greet_user(username):
print("Hello {}. You're Awesome!".format(user))
greet_user('John Doe')
Hello John Doe. You're Awesome!
Strings are just like Arrays. Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.[ ] syntax, and like Java and C++, Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'.s = 'Hi'
print(s[1]) # Returns the second character
print(len(s)) # Finds length of the string variable.
print(s + ' there') # Concatenates value stored in variable `s` and ' there'
i 2 Hi there
pi = 3.14
# The below line will raise an exception/error.
# You cannot concatenate sting and float
# text = 'The value of pi is ' + pi
# You can do it by converting float to string by using str()
text = 'The value of pi is ' + str(pi)
print(text)
The value of pi is 3.14
# Return a copy of the string with all the cased characters converted to lowercase.
text.lower()
'the value of pi is 3.14'
# Return a copy of the string with all the cased characters converted to uppercase.
text.upper()
'THE VALUE OF PI IS 3.14'
# Return True if all characters in the string are alphabetic and there is at least one character,
# False otherwise.
text.isalpha()
False
# Return True if all characters in the string are numeric characters, and there is at least one character,
# False otherwise.
text.isnumeric()
False
# Return True if string starts with the prefix, otherwise return False.
text.startswith('T')
True
# Returns True if the text contains a substring, otherwise return False.
# The below will return True since 'pi' is substring of text.
'pi' in text
True
# Return the lowest index in the string where substring sub is found.
# Returns -1 if not found.
text.find('pizza')
-1
csv = "abc,ced,def,hij"
# Return a list of the words in the string, using `sep` (argument) as the delimiter string.
csv.split(",")
['abc', 'ced', 'def', 'hij']
IF...ELIF...ELSEStatements
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.
The syntax of the if..elif..else statement is −
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
if 'pi' in text.lower():
print("Text contains the substring 'pi'")
pi_index = text.find('pi')
print(pi_index)
Text contains the substring 'pi' 13
if 4 < 3:
# pass is a command to do nothing
pass
elif 'pi' in text.lower():
print('Text contains the substring \'pi\'')
else:
pass
Text contains the substring 'pi'